//
//  PictureBrowserCell.swift
//  WeiBlog
//
//  Created by apple on 15/10/28.
//  Copyright © 2015年 xiang. All rights reserved.
//

import UIKit
import SDWebImage
class PictureBrowserCell: UICollectionViewCell {

    var picURL:NSURL?{
        
        didSet{
            
            let URLStr = picURL!.absoluteString
            //根据缩略图url,获取中等图url
            let newURLStr = URLStr.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
            
            let placeHoldImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(URLStr)
            
            //切换到下一张图片,还是要显示进度指示器
            self.progressView.hidden = false
            
            //用这个方法可以监听,下载进度,和完成回调
            imageView.sd_setImageWithURL(NSURL(string: newURLStr),
                placeholderImage: placeHoldImage,
                options: [SDWebImageOptions.RefreshCached,SDWebImageOptions.RetryFailed],
                progress: { (current, total) -> Void in
                    
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        
                        let a = CGFloat(current) / CGFloat(total)
                        
                        self.progressView.progress = a
                    })
                    
                }){ (image, _, _, _) -> Void in
                    
                    self.progressView.hidden = true
            }
            //还原缩放比例
            imageView.transform = CGAffineTransformIdentity
            
            scrollView.contentSize = CGSizeZero
            scrollView.contentInset = UIEdgeInsetsZero
            scrollView.contentOffset = CGPointZero
            
    
            //imageview的大小和位置要根据图片确定
            imageView.center = scrollView.center
            
            if let image = imageView.image {
                
                imageView.bounds.size.width = ScreenWidth
                
                imageView.bounds.size.height = image.size.height * ScreenWidth / image.size.width
            }
            
            if imageView.bounds.size.height > ScreenHeight{
                
                imageView.frame.origin.y = 0

            }
            
            scrollView.contentSize = imageView.bounds.size
            
        }
    }
    
    override init(frame: CGRect) {
            super.init(frame: frame)
            setUI()
        }
        
    required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    // MARK: ----懒加载
    
    ///用于图片的缩放
    private lazy var scrollView:UIScrollView = UIScrollView()
    ///展示图片
    lazy var imageView:UIImageView = UIImageView()
    ///  进度视图
    private lazy var progressView:ProgressView = ProgressView()
    
    private func setUI(){
        //添加控件
        contentView.addSubview(scrollView)
        //注意是加在scrollView 上的
        scrollView.addSubview(imageView)
        scrollView.addSubview(progressView)
        
        progressView.center = CGPoint(x: ScreenWidth * 0.5, y: ScreenHeight * 0.5)
        
        scrollView.frame = CGRect(x: 0, y: 0, width: bounds.width - 20, height: bounds.height)
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        scrollView.delegate = self
        imageView.userInteractionEnabled = true
        
        
    }
    
    // MARK:---定义显示进度视图
    private class ProgressView:UIView{
        
        var progress:CGFloat = 0{
            didSet{
                //每次赋值的时候,就重新绘图
                setNeedsDisplay()
            }
        }
        
        init(){
            super.init(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
            
            layer.cornerRadius = 20
            layer.masksToBounds = true
            
            backgroundColor = UIColor.blackColor()
            alpha = 0.6
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private override func drawRect(rect: CGRect) {
            let center = CGPoint(x: rect.width * 0.5, y: rect.height*0.5)
            let radius = rect.width * 0.4
            let start = CGFloat(-M_PI_2)
            let end = start + progress * CGFloat(M_PI) * 2
            
            let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: start, endAngle: end, clockwise: true)
            
            // 添加到中心点的连线
//            path.addLineToPoint(center)
//            path.closePath()
            
            path.lineWidth = 4
            path.lineCapStyle = CGLineCap.Round
            
            UIColor(red: 1, green: 1, blue: 1, alpha: 1).setStroke()
//            UIColor.whiteColor().setStroke()
            
            path.stroke()
        }
    }
}

// MARK:---缩放代理
extension PictureBrowserCell:UIScrollViewDelegate
{
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imageView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        //view是指缩放的view,就是上面的函数返回view
        
        //计算目的:缩放之后,imageView的大小和位置,都会变化,所以需要重新定位
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        
        offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        
        offsetX = offsetX < 0 ? 0 : offsetX

        scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: offsetY, right: offsetX)

    }
}












